package com.ljw.security.springSecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @FileName WebSecurityConfig
 * @Description TODO     springsecurity配置
 * @Author ljw
 * @Date 2020/8/31 17:58
 * @Version 1.0
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //配置用户信息服务
    @Bean
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities(new String[]{"p1"}).build());
        manager.createUser(User.withUsername("lisi").password("456").authorities(new String[]{"p2"}).build());
        return manager;
    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    //配置安全拦截机制--认证授权的条件
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasAnyAuthority("p1")    // 访问/r/r1资源的 url需要拥有p1权限
                .antMatchers("/r/r2").hasAnyAuthority("p2")    // 访问/r/r2资源的 url需要拥有p2权限
                .antMatchers("/r/**").authenticated()   // url匹配/r/**的资源，经过认证后才能访问
                .anyRequest().permitAll()                               //其他url完全开放
                .and()
                .formLogin().successForwardUrl("/login-success");    //支持form表单认证，认证成功后转向controller方法的路径：/login-success。
    }
}
